package com.web.feign.interceptor;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import com.web.common.properties.TokenConfigEntity;
import com.web.common.security.FeignInnerEntity;
import com.web.common.tool.SysDefaultAdmin;
import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * Feign请求设置登录信息。
 * 注：如果设置了inner==Y 则认为内部调用，不会再获取主请求的header信息，因为可能是异步调用导致获取不到主请求的信息！！
 * @author zhouhui
 * @since 1.0.0
 */
public class LoginTokenFeignInterceptor implements RequestInterceptor{
	
	@Autowired
	private HttpServletRequest httpServletRequest;
	
	@Autowired
	private TokenConfigEntity tokenConfig;
	
	@Autowired
	private SysDefaultAdmin sysDefaultAdmin;

	@Override
	public void apply(RequestTemplate template) {
		Collection<String> values = template.headers().get(FeignInnerEntity.HTTP_HEADER_INNER);
		if(values != null && !values.isEmpty()) {
			if(values.contains(FeignInnerEntity.HTTP_INNER_VALUE)) {
				template.header(tokenConfig.getHeadTokenName(), sysDefaultAdmin.createDefaultToken());
			}else {
				String token = httpServletRequest.getHeader(tokenConfig.getHeadTokenName());
				template.header(tokenConfig.getHeadTokenName(), token);
			}
		}else {
			String token = httpServletRequest.getHeader(tokenConfig.getHeadTokenName());
			template.header(tokenConfig.getHeadTokenName(), token);
		}
	}
}
